<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>午夜聊天室</title>
	<style>
	html,body,div,input,span{border: 0;margin: 0;padding:0;outline: 0;box-sizing: border-box;}
		.screen{width: 100%;height: 300px;background-color: #666;color: snow;padding: 5px 8px;overflow: auto;}
		.input{width: 90%;border: 1px solid #333;padding:0px 5px;line-height: 34px;}
		.send{width: 10%;float:right;display: inline-block;box-sizing: border-box;border: 1px solid #8ac;text-align:center;line-height: 34px;background-color: #8aa;color: snow;cursor: pointer;}
		.text_left{text-align: left;width: 100%;}
		.text_right{text-align: right;width: 100%;}
	</style>
</head>
<body>
	<div class="screen" id="screen"></div>
	<input type="text" placeholder="请输入消息" class="input" id="input"><span class="send" id="send">send</span>
	

	<script>
		var screen = document.getElementById('screen');
		var input = document.getElementById('input');
		var send = document.getElementById('send');
		var userId = new Date().getTime();


		/*send点击事件函数*/
		send.onclick = function(){
			var time = new Date().getTime();
			var msg = "<div>" + input.value + "</div>";
			screen.innerHTML += msg;
			localStorage[time] = JSON.stringify({userid:sessionStorage['userid'],msg:msg}) ; // 用JSON.stringify()将对象转化成字符串对象才可以存储在localStorage中
			
			input.value = '';
			
			screen.scrollTop = screen.scrollHeight;//保持screen显示最新消息（显示底部消息）
		}

		/*通过遍历将localStorage中的数据显示到screen中*/
		setInterval(function(){ //定时器的作用：使得俩个页面同时实时加载localStorage中的数据
			var str = ''; //防止每1000ms加载重复数据
			for(var i in localStorage){
				//console.dir(localStorage[i]);
				var id = JSON.parse(localStorage[i]);
				console.dir(id['userid']);
				if(id['userid'] == sessionStorage['userid']){
					str += ' <div class="text_left">' + id['msg'] + '</div>';
				}else{
					str += ' <div class="text_right">' + id['msg'] + '</div>';
				}
				
				screen.innerHTML = str;
				screen.scrollTop = screen.scrollHeight;
			}
		}, 1000)
		

		/*绑定ENTER键位 ----enter对应keycode == 13*/
		document.onkeyup = function (event) {
            var e = event || window.event;
            var keyCode = e.keyCode || e.which;
            switch (keyCode) {
                case 13:
                    send.onclick();
                    break;
                default:
                    break;
	        }
	    }

	    /*给sessionStorage赋值，用来识别用户*/
	    if(!sessionStorage.userid){
	    	sessionStorage.userid = userId;
	    }
	</script>
</body>
</html>